package ru.vsu.cs.kis.elections.socketexchenge.commands;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class PingCommand extends Command {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4059293341721709210L;

	private Integer ping = -1;

	public PingCommand() {
	}

	public PingCommand(OutputStream aOutStr, InputStream aInStr) {
		super(aOutStr, aInStr);
	}

	public Integer getPing() {
		return (ping );
	}

	@Override
	public Integer executeOnClient() throws IOException {
		long timeStart = System.nanoTime();
		(new CommandName(aOutStr, aInStr, this)).executeOnClient();
		BufferedInputStream input = new BufferedInputStream(aInStr);
		if (input.read() >= 0) {
			ping = (int) (System.nanoTime()/ 10000 - timeStart/ 10000);
			return (1);
		}
		return (-1);
	}

	@Override
	public Integer executeOnServer() throws IOException {		
		long timeStart = System.nanoTime();
		
		// прилипить проверку подключения к бд

		BufferedOutputStream output = new BufferedOutputStream(aOutStr);
		ping = (int) (System.nanoTime() - timeStart);
		output.write(ping);		
		output.flush();
		return (1);
	}

}
